/** WPI CS509 cisco Stratego Username/Password
 * 
 */

package edu.wpi.cs509.representation;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;


/**
 * This class add password to the username base-class.
 * @author sparadis
 * @author saerb - hash
 *
 */
@MappedSuperclass
public class UserPair extends UserName {
	
	/** 
	 * password
	 */
	@Column(name = "password")
	private   String  password;
	/**
	 * Add a little salt to the password for hashing
	 */
	private  static final String  salt = "SALT!!!!wpi509";

	/**
	 * serializable version number
	 */
	private static final long serialVersionUID = 1L;
	
	public UserPair()
	{
		super();
	}
	
	/**
	 * Constructor, sets username. 
	 * @param username
	 */
	public UserPair(String username) {
		super(username);
	}
	
	/**
	 * Constructor, sets username/password. 
	 * Note that password may be null if it is not known.
	 * @param username
	 * @param password
	 */
	public UserPair(String username, String password) {
		super(username);
		this.password = this.hash(password);
	}

	/**
	 * Get the password.
	 * @return String password.
	 */
	public String getPassword() { return password; }
	
	/**
	 * Set the password.
	 * @param pw
	 * @return 0
	 */
	public int setPassword(String pw) { 
		this.password = this.hash(pw); 
		return 0; 
	}
	
	/**
	 * Custom toString
	 */
	public String toString() {
		return (super.toString() + ", password: " + password);
	}
	
	/**
	 * Checks if an input-password is a user's saved password.
	 * @param pw the password to check
	 * @return true/false for validity
	 */
	public boolean validatePassword(String pw){
		if (pw.equals(this.password)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * Creates a hashed string to store a user's password.
	 * 
	 * @param pw the string password to make a hash for
	 * @return output the hash result
	 */
	private String hash (String pw) {
		pw = pw + salt;
		String output = null;
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			md5.update(pw.getBytes());
			BigInteger hash = new BigInteger(1, md5.digest());
			output = hash.toString(16);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Unable to make a hash for this user's password: "+this.getUsername());
			e.printStackTrace();
		}
		return output;
	}
}

